import datetime
import copy
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import Core.Gadget as Gadget
import SystematicFactors.General
from SystematicFactors.General import Load_Systematic_Market_Factor, Load_Systematic_Factor, Plot_Systematic_Factor
from Analysis.RegressionAnalysis import RollingRegression_IdxBased
#
def Rate_Correlation():
    #
    df_Repo1 = Load_Systematic_Market_Factor(database, "Repo001")
    df_Repo7 = Load_Systematic_Market_Factor(database, "Repo007")
    df_DR1 = Load_Systematic_Market_Factor(database, "DRepo001")
    df_DR7 = Load_Systematic_Market_Factor(database, "DRepo007")
    df_Shibor1m = Load_Systematic_Market_Factor(database, "Shibor_1M")
    df_Shibor3m = Load_Systematic_Market_Factor(database, "Shibor_3M")
    pass


def Plot_And_Test(database):
    #
    # df = Load_Systematic_Market_Factor(database, "Tbond_YTM_1Y")
    # df["Avg20"] = df["Tbond_YTM_1Y"].rolling(window=60).mean()
    # df["Avg5"] = df["Tbond_YTM_1Y"].rolling(window=20).mean()
    # #
    # df = RollingRegression_IdxBased(df, window=60, fieldName="Avg20")
    # print(df.tail(20))
    # #
    # # df.to_csv("d://regression.csv")
    #
    # fig, ax1 = plt.subplots()
    # ax2 = ax1.twinx()
    # df.plot(x="date", y=["Avg20"], color='r', ax=ax1)
    # df.plot(x="date", y=["Slope"], color='b', grid=True, ax=ax2)
    #
    # # ax1.set_ylabel('Net Unit Value')
    # print(df.describe())
    # plt.show()

    ###
    df = Load_Systematic_Market_Factor(database, "Credit_Spread_1Y")
    df["Avg20"] = df["Credit_Spread_1Y"].rolling(window=60).mean()
    df["Avg5"] = df["Credit_Spread_1Y"].rolling(window=20).mean()
    #
    df = RollingRegression_IdxBased(df, window=60, fieldName="Avg20")
    print(df.tail(20))

    fig, ax1 = plt.subplots()
    ax2 = ax1.twinx()
    df.plot(x="date", y=["Avg20"], color='r', ax=ax1)
    df.plot(x="date", y=["Slope"], color='b', grid=True, ax=ax2)
    plt.show()


#
def Calculate_Financial_Cycle(database):
    # 季度平滑
    df_Tbond = Load_Systematic_Market_Factor(database, "Tbond_YTM_1Y")
    df_Tbond["Avg"] = df_Tbond["Tbond_YTM_1Y"].rolling(window=60).mean()
    df_Tbond = RollingRegression_IdxBased(df_Tbond, window=60, fieldName="Avg")
    print(df_Tbond.tail())
    #
    df_Credit = Load_Systematic_Factor(database, "Credit_Spread_1Y")
    df_Credit["Avg"] = df_Credit["Credit_Spread_1Y"].rolling(window=60).mean()
    df_Credit = RollingRegression_IdxBased(df_Credit, window=60, fieldName="Avg")
    print(df_Credit.tail())

    #
    datetime1 = datetime.datetime(2010, 5, 1)
    datetime2 = datetime.datetime(2020, 5, 10)
    #
    data = []
    datetimes = Gadget.generate_begin_date_of_month_list(datetime1, datetime2)
    for dt in datetimes:
        print(dt)
        roe_trend = 0
        pmi_trend = 0
        industry_trend = 0
        shibor_trend = 0
        cpi_trend = 0
        tbond10y_trend = 0
        ir_trend = 0
        credit_spread_trend = 0

        # TBond-IR
        df_tmp = df_Tbond[df_Tbond["date"] <= dt]
        latest = df_tmp.iloc[-1]
        if latest["Slope"] > 0:
            ir_trend = 1
        else:
            ir_trend = -1

        #
        df_tmp = df_Credit[df_Credit["date"] <= dt]
        latest = df_tmp.iloc[-1]
        if latest["Slope"] > 0:
            credit_spread_trend = 1
        else:
            credit_spread_trend = -1

        # 确认周期
        print(ir_trend, credit_spread_trend)
        #
        ddm_period = 0
        if ir_trend > 0 and credit_spread_trend > 0:
            ddm_period = 1
        elif ir_trend > 0 and credit_spread_trend < 0:
            ddm_period = 2
        elif ir_trend < 0 and credit_spread_trend > 0:
            ddm_period = 3
        elif ir_trend < 0 and credit_spread_trend < 0:
            ddm_period = 4
        #
        data.append([dt, dt, ddm_period])
        a = 0
    #
    df_factor = pd.DataFrame(data, columns=["ReportDate", "ReleaseDate", "DDM_Cycle"])
    print(df_factor)
    SystematicFactors.General.SaveSystematic_MacroFactorToDatabase(database, df_factor, factorName="DDM_Cycle")


if __name__ == '__main__':
    #
    from Core.Config import *
    pathfilename = os.getcwd() + "\..\Config\config2.json"
    config = Config(pathfilename)
    database = config.DataBase("JDMySQL")
    realtime = config.RealTime()
    #
    datetime1 = datetime.datetime(2000, 1, 1)
    datetime2 = datetime.datetime(2020, 5, 11)
    #
    # Calculate_Financial_Cycle(database)
    Plot_And_Test(database)